package com.bosssoft.trainee.gateway.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authorization.AuthorizationDecision;
import org.springframework.security.authorization.ReactiveAuthorizationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.authorization.AuthorizationContext;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import reactor.core.publisher.Mono;

/**
 * @Author: wuxin
 * @Project: rbac-SpringCloud
 * @Date: 2022/7/15
 * @Description:
 */
@Slf4j
@Component
public class MyAuthorizationManager implements ReactiveAuthorizationManager<AuthorizationContext> {
    @Override
    public Mono<AuthorizationDecision> check(Mono<Authentication> authentication, AuthorizationContext authorizationContext) {
        return authentication.map(auth -> {
            String username = (String) auth.getPrincipal();
            log.info("MyAuthorizationManager username = {}", username);

            if (StringUtils.hasLength(username)) {
                return new AuthorizationDecision(true);
            }
            return new AuthorizationDecision(false);
        }).defaultIfEmpty(new AuthorizationDecision(false));
    }
}